﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using CarolLib.WinService;
using System.Configuration;
using System.IO;
using CarolLib;
using HQDBF;
using System.Data;

namespace CarolLib.Task
{
    /// <summary>
    /// 按日从DBF定期保存所有股票价格的服务
    /// </summary>
    /// <remarks>
    /// 代码编写：<author>LANCEZHANG-PC\zhangxl</author><br/>
    /// 编写时间：<datetime>2012-10-16 5:01 PM</datetime>
    /// </remarks>
    public class DBFHistoryPrice : IBasicTask
    {
        #region Members

        static string begintime = ConfigurationManager.AppSettings["BeginTime"];
        static string OutputPath = ConfigurationManager.AppSettings["OutputPath"];
        static readonly string CHK = "SELECT HQZQJC AS LastDate FROM SJSHQ WHERE HQZQDM='000000'";
        static readonly string SHSP = "SELECT S1 AS Code, S8 AS CurrentPrice FROM SHOW2003 WHERE S1>='600000' AND S1<='601999'";
        static readonly string SZSP = "SELECT HQZQDM AS Code, HQZJCJ AS CurrentPrice FROM SJSHQ WHERE (HQZQDM>='000001' AND HQZQDM<='002615') OR (HQZQDM>='300001' AND HQZQDM<='300261')";

        PriceQuery query = new PriceQuery();

        #endregion

        #region IBasicTask Members

        public void Exit()
        {
        }

        public void Init()
        {
        }

        public void Execute()
        {
            bool valid = Validate();

            if (!valid)
                return;

            Log.Info("开始执行...");
            Log.Info("开始获取行情价格...");
            DataTable prices = GetPrice();
            Log.Info("获取行情价格成功");

            SavePrices(prices);
        }

        private bool Validate()
        {
            bool valid = true; 
            if (!Directory.Exists(OutputPath))
            {
                Log.Error("指定的输出路径 {0} 不存在", OutputPath);
                valid = false;
            }

            try
            {
                query.GetBuyPriceX("600570", 1);
                query.GetBuyPriceX("000004", 1);
                Log.Info("行情接口测试成功");
            }
            catch (Exception ex)
            {
                Log.Instance.Fatal("测试行情接口失败", ex);
                valid = false;
            }
 
            if (DateTime.Compare(DateTime.Now,Convert.ToDateTime(begintime))<0)
            {
                Log.Info("未到达设定的时间（" + begintime + "）内，暂不执行");
                valid = false;
            }

            var tb = query.OpenQueryTable(CHK, false);
            if (tb.Rows.Count > 0 && tb.Rows[0][0].ToString() != DateTime.Today.ToString("yyyyMMdd"))
            {
                Log.Info("当前行情是交易日(" + tb.Rows[0][0].ToString() + ")，" + "不是今天（" + DateTime.Today.ToString("yyyyMMdd") + "）,暂不执行");
                valid = false;
            }

            return valid;
        }

        private void SavePrices(DataTable prices)
        {
            foreach (DataRow row in prices.Rows)
            {
                string path = OutputPath + row["Code"] + ".txt";
                DateTime lastday = DateTime.MinValue;

                //是否今天已经存了
                if (File.Exists(path))
                {
                    string last = File.ReadAllLines(path).LastOrDefault();
                    DateTime.TryParse(last.Split(',')[0], out lastday);
                }

                if (lastday == DateTime.Today)
                {
                    Log.Info("{0} - 今天已保存", row["Code"]);
                    continue;
                }

                //保存今天数据
                using (StreamWriter sw = File.Exists(path) ? File.AppendText(path) : File.CreateText(path))
                {
                    sw.WriteLine("{0},{1}", DateTime.Today.ToString("yyyy-MM-dd"), row["CurrentPrice"]);
                }

                Log.Info("{0},{1} - 已保存", row["Code"], row["CurrentPrice"]);
            }

            Log.Info("保存全部行情价格成功");
        }

        private DataTable GetPrice()
        {
            DataTable prices = query.OpenQueryTable(SHSP, true);

            prices.Merge(query.OpenQueryTable(SZSP, false));

            return prices;
        }

        #endregion
    }
}
